#!/bin/bash

echo "================================"
echo "DVHealth Backend 启动脚本"
echo "================================"

# 检查是否在虚拟环境中
if [ -z "$VIRTUAL_ENV" ]; then
    echo "正在激活虚拟环境..."
    if [ -f .venv/bin/activate ]; then
        source .venv/bin/activate
    else
        echo "错误: 未找到虚拟环境，请先创建虚拟环境"
        echo "运行: python -m venv .venv"
        exit 1
    fi
fi

# 检查依赖是否安装
echo "正在检查依赖..."
if ! python -c "import django" 2>/dev/null; then
    echo "正在安装依赖..."
    pip install -e .
    if [ $? -ne 0 ]; then
        echo "错误: 依赖安装失败"
        exit 1
    fi
fi

# 检查数据库迁移
echo "正在检查数据库迁移..."
if python manage.py showmigrations --plan | grep -q "\[ \]"; then
    echo "正在执行数据库迁移..."
    python manage.py makemigrations
    python manage.py migrate
fi

# 创建日志目录
mkdir -p logs

# 启动开发服务器
echo "================================"
echo "正在启动 Django 开发服务器..."
echo "API 文档: http://localhost:8000/api/schema/swagger-ui/"
echo "管理后台: http://localhost:8000/admin/"
echo "================================"
python manage.py runserver